<template>
  <div class="box">
    <!--激活弹窗-->
    <div class="text-right">
      <el-popover placement="left" width="160" trigger="click">
        <el-checkbox-group v-model="checkboxVal">
          <div v-for="(item) in formTheadOptions" :key="item.key" class="m-5">
            <el-checkbox :label="item">{{ item.name }}</el-checkbox>
          </div>
        </el-checkbox-group>
        <el-button slot="reference" type="primary" icon="el-icon-s-tools">点击这里</el-button>
      </el-popover>
    </div>
    <!--table-->
    <el-table
      :key="key"
      :data="tableData"
      border
      class="table mt-15"
      stripe
      highlight-current-row
      header-cell-class-name="table-header">
      <el-table-column type="index" fixed label="序号" width="55" align="center"></el-table-column>
      <el-table-column prop="name" label="名称" width="180" />
      <el-table-column
        v-for="fruit in formThead"
        :key="fruit.key"
        :prop="fruit.key"
        :label="fruit.name">
        <!--        用这个也行，用prop也行-->
        <!--        <template v-slot="scope">-->
        <!--          {{ scope.row[fruit.key] }}-->
        <!--        </template>-->
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="160">
        <template v-slot="scope">
          <el-button type="primary" size="mini">编辑</el-button>
          <el-button type="danger" size="mini">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  name: 'DynamicTable',
  data() {
    return {
      tableData: [],
      key: 1, // table key
      formTheadOptions: [], // 原始数组，用来过滤
      checkboxVal: [], // checkboxVal
      formThead: [] // 默认表头 Default header
    }
  },
  watch: {
    checkboxVal(valArr) {
      const valNames = valArr.map((item) => item.key)
      this.formThead = this.formTheadOptions.filter((i) => valNames.indexOf(i.key) >= 0)
      // 为了保证 table 每次都会重渲
      this.key = this.key + 1
    }
  },
  created() {
    this.getTableHeader()
    this.getTableData()
  },
  methods: {
    // 获取显示隐藏的header
    getTableHeader() {
      const arr = [
        { key: 'position', name: '职位' },
        { key: 'iPhone', name: '联系方式' },
        { key: 'remark', name: '备注' }
      ]
      this.formTheadOptions = arr
      this.checkboxVal = arr
      this.formThead = arr
    },
    // 获取table数据
    getTableData() {
      this.tableData = [
        {
          name: '数据1',
          position: '嘿嘿嘿',
          iPhone: '15149174852',
          remark: '前端'
        },
        {
          name: '数据2',
          position: '哈哈哈哈',
          iPhone: '13141548596',
          remark: '运维'
        }
      ]
    }
  }
}
</script>

<style scoped>

</style>
